<!DOCTYPE HTML>
<html>
<head>
<!--jQuery dependencies-->
    <link rel="stylesheet" href="../../pqgrid/css/jquery-ui-base-1.9.1.css" />
    <script src="../../pqgrid/js/jquery-1.9.1.min.js"></script>    
    <script src="../../pqgrid/js/jquery-ui-1.9.2.min.js"></script>
<!--PQ Grid files-->
    <link rel="stylesheet" href="../../pqgrid/pqgrid.min.css" />
    <script src="../../pqgrid/pqgrid.min.js"></script>
<!--PQ Grid Office theme-->
    <link rel="stylesheet" href="../../pqgrid/themes/office/pqgrid.css" />

    <style type="text/css">
	div.pq-toolbar button
	{
	    margin:0px 5px;
	}
	button.delete_btn
	{
	    margin:-3px 0px;
	}
	tr.pq-row-delete
	{
	    text-decoration:line-through;         
	}
	tr.pq-row-delete td
	{
	    background-color:pink;   
	}
	</style>

<script>
    $(function () {
        //called when save changes button is clicked.
        function saveChanges() {
            var grid = $grid.pqGrid('getInstance').grid;

            //debugger;
            //attempt to save editing cell.
            if (grid.saveEditCell() === false) {
                return false;
            }

            var isDirty = grid.isDirty();
            if (isDirty) {
                //validate the new added rows.                
                var addList = grid.getChanges().addList;
                //debugger;
                for (var i = 0; i < addList.length; i++) {
                    var rowData = addList[i];
                    var isValid = grid.isValid({ "rowData": rowData }).valid;
                    if (!isValid) {
                        return;
                    }
                }
                var changes = grid.getChanges({ format: "byVal" });

                //post changes to server 
                $.ajax({
                    dataType: "json",
                    type: "POST",
                    async: true,
                    beforeSend: function (jqXHR, settings) {
                        grid.showLoading();
                    },
                    url: "/pro/products/batch", //for ASP.NET, java                                                
                    data: { list: JSON.stringify(changes) },
                    success: function (changes) {
                        //debugger;
                        grid.commit({ type: 'add', rows: changes.addList });
                        grid.commit({ type: 'update', rows: changes.updateList });
                        grid.commit({ type: 'delete', rows: changes.deleteList });

                        grid.history({ method: 'reset' });
                    },
                    complete: function () {
                        grid.hideLoading();
                    }
                });
            }
        }
        var obj = {
            hwrap: false,
            resizable: true,
            rowBorders: false,
            virtualX: true,
            numberCell: { show: true },
            trackModel: {on: true}, //to turn on the track changes.            
            toolbar: {
                items: [
                    { type: 'button', icon: 'ui-icon-plus', label: 'New Product', listener:
                        { "click": function (evt, ui) {
                            //append empty row at the end.                            
                            var rowData = { UnitPrice: 1, ProductID: 34, UnitPrice: 0.2 }; //empty row
                            var rowIndx = $grid.pqGrid("addRow", { rowData: rowData, checkEditable: true });
                            $grid.pqGrid("goToPage", { rowIndx: rowIndx });
                            $grid.pqGrid("editFirstCellInRow", { rowIndx: rowIndx });
                        }
                        }
                    },
                    { type: 'separator' },
                    { type: 'button', icon: 'ui-icon-disk', label: 'Save Changes', cls: 'changes', listener:
                        { "click": function (evt, ui) {
                            saveChanges();
                        }
                        },
                        options: { disabled: true }
                    },
                    { type: 'button', icon: 'ui-icon-cancel', label: 'Reject Changes', cls: 'changes', listener:
                        { "click": function (evt, ui) {
                            $grid.pqGrid("rollback");
                            $grid.pqGrid("history", { method: 'resetUndo' });
                        }
                        },
                        options: { disabled: true }
                    },
                    { type: 'button', icon: 'ui-icon-cart', label: 'Get Changes', cls: 'changes', listener:
                        { "click": function (evt, ui) {
                            var changes = $grid.pqGrid("getChanges", { format: 'raw' });
                            try {
                                console.log(changes);
                            }
                            catch (ex) { }
                            alert("Please see the log of changes in your browser console.");
                        }
                        },
                        options: { disabled: true }
                    },
                    { type: 'separator' },
                    { type: 'button', icon: 'ui-icon-arrowreturn-1-s', label: 'Undo', cls: 'changes', listener:
                        { "click": function (evt, ui) {
                            $grid.pqGrid("history", { method: 'undo' });
                        }
                        },
                        options: { disabled: true }
                    },
                    { type: 'button', icon: 'ui-icon-arrowrefresh-1-s', label: 'Redo', listener:
                        { "click": function (evt, ui) {
                            $grid.pqGrid("history", { method: 'redo' });
                        }
                        },
                        options: { disabled: true }
                    }
                ]
            },
            scrollModel: {
                autoFit: true
            },
            selectionModel: {
                type: 'cell'
            },
            swipeModel: { on: false },
            editModel: {
                onBlur: 'validate',
                saveKey: $.ui.keyCode.ENTER
            },
            editor: {
                select: true
            },
            title: "<b>Batch Editing</b>",
            history: function (evt, ui) {
                var $grid = $(this);
                if (ui.canUndo != null) {
                    $("button.changes", $grid).button("option", { disabled: !ui.canUndo });
                }
                if (ui.canRedo != null) {
                    $("button:contains('Redo')", $grid).button("option", "disabled", !ui.canRedo);
                }
                $("button:contains('Undo')", $grid).button("option", { label: 'Undo (' + ui.num_undo + ')' });
                $("button:contains('Redo')", $grid).button("option", { label: 'Redo (' + ui.num_redo + ')' });
            },
            colModel: [
                { title: "Product ID", dataType: "integer", dataIndx: "ProductID", editable: false, width: 80 },
                { title: "Product Name", width: 165, dataType: "string", dataIndx: "ProductName",
                    validations: [
                        { type: 'minLen', value: 1, msg: "Required" },
                        { type: 'maxLen', value: 40, msg: "length should be <= 40" }
                    ]
                },
                { title: "Quantity Per Unit", width: 140, dataType: "string", align: "right", dataIndx: "QuantityPerUnit",
                    validations: [
                        { type: 'minLen', value: 1, msg: "Required." },
                        { type: 'maxLen', value: 20, msg: "length should be <= 20" }
                    ]
                },
                { title: "Unit Price", width: 100, dataType: "float", align: "right", dataIndx: "UnitPrice",
                    validations: [{ type: 'gt', value: 0.5, msg: "should be > 0.5"}],
                    render: function (ui) {
                        //debugger;
                        var cellData = ui.cellData;
                        if (cellData != null) {
                            return "$" + parseFloat(ui.cellData).toFixed(2);
                        }
                        else {
                            return "";
                        }
                    }
                },
                { hidden: true },
                { title: "Units In Stock", width: 100, dataType: "integer", align: "right", dataIndx: "UnitsInStock",
                    validations: [{ type: 'gte', value: 1, msg: "should be >= 1" },
                                 { type: 'lte', value: 1000, msg: "should be <= 1000" }
                            ]
                },
                { title: "Discontinued", width: 100, dataType: "bool", align: "center", dataIndx: "Discontinued",
                    editor: { type: "checkbox", subtype: 'triple', style: "margin:3px 5px;" },
                    validations: [{ type: 'nonEmpty', msg: "Required"}]
                },
                { title: "", editable: false, minWidth: 83, sortable: false,
                    render: function (ui) {
                        return "<button type='button' class='delete_btn'>Delete</button>";
                    }
                }
            ],
            pageModel: { type: "local", rPP: 20 },
            dataModel: {
                dataType: "JSON",
                location: "remote",
                recIndx: "ProductID",
                url: "/pro/products/get", //for ASP.NET
                //url: "/pro/products.php", //for PHP
                getData: function (response) {
                    return { data: response.data };
                }
            },
            refresh: function () {
                $("#grid_editing").find("button.delete_btn").button({ icons: { primary: 'ui-icon-scissors'} })
                .unbind("click")
                .bind("click", function (evt) {
                    var $tr = $(this).closest("tr");
                    var obj = $grid.pqGrid("getRowIndx", { $tr: $tr });
                    var rowIndx = obj.rowIndx;
                    $grid.pqGrid("addClass", { rowIndx: rowIndx, cls: 'pq-row-delete' });

                    var ans = window.confirm("Are you sure to delete row No " + (rowIndx + 1) + "?");
                    $grid.pqGrid("removeClass", { rowIndx: rowIndx, cls: 'pq-row-delete' });
                    if (ans) {
                        $grid.pqGrid("deleteRow", { rowIndx: rowIndx });
                    }
                });
            }
        };
        var $grid = $("#grid_editing").pqGrid(obj);
    });
        
</script>    
</head>
<body>

<div id="grid_editing" style="margin: auto;">
</div>

</body>

</html>
